﻿using Cheems.Interface.Models.UserManagement;
using Cheems.Interface.SQL;
using Cheems.Interface.UserManagement;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace Cheems.Service.UserManagement
{
    /// <summary>
    /// 用户管理服务
    /// </summary>
    public class UserManagementService : IUserManagement
    {
        IBaseRepository<T_User> _userDb;
        public event Action<string> OnMessageReminder;
        public event Action<List<T_User>> OnUserInfoChanged;
        public event Action<T_User> OnUserLogin;

        public UserManagementService(IBaseRepository<T_User> userDb)
        {
            this._userDb = userDb;
        }



        public async Task<bool> Login(T_User user)
        {
            List<T_User> filteredUsers = await QueryUser(
                it => it.Name == user.Name
                && it.PasswordSha256Hash == user.PasswordSha256Hash);
            if (filteredUsers.Any())
            {
                OnMessageReminder?.Invoke("登录成功。");
                OnUserLogin?.Invoke(filteredUsers[0]);
                return true;
            }
            else
            {
                OnMessageReminder?.Invoke("登录失败，用户名或密码错误。");
                return false;
            }
        }


        public async Task<bool> AddUser(T_User user)
        {
            List<T_User> sameNameAccount = await QueryUser(it => it.Name == user.Name);
            if (sameNameAccount.Count >= 1)
            {
                return false;
            }

            bool success = (await this._userDb.Insert(user, true) == 1) ? true : false;
            if (success)
            {
                OnMessageReminder?.Invoke("已存在同名用户。");
                OnUserInfoChanged?.Invoke(await QueryAllUser());
            }
            return success;
        }

        public async Task<bool> RemoveUser(T_User user)
        {
            int deleteCount = await this._userDb.Delete(it => it.Name == user.Name
                && it.PasswordSha256Hash == user.PasswordSha256Hash);
            if (deleteCount > 0)
            {
                OnMessageReminder?.Invoke($"移除用户{user.Name}成功。");
                OnUserInfoChanged?.Invoke(await QueryAllUser());
                return true;
            }
            else
            {
                OnMessageReminder?.Invoke($"移除用户{user.Name}失败。");
                return false;
            }
        }

        public async Task<List<T_User>> QueryAllUser()
        {
            return await this._userDb.QueryAsync(it => true);
        }

        public async Task<List<T_User>> QueryUser(Expression<Func<T_User, bool>> whereExpression)
        {
            return await this._userDb.QueryAsync(whereExpression);
        }
    }
}
